package org.oslims.server.dao.hbm;

import java.util.List;

import org.hibernate.Query;
import org.oslims.domain.Mixture;
import org.oslims.server.dao.MixtureDao;

public class HbmMixtureDao extends HbmGenericDao<Mixture, Long> implements MixtureDao {

	@Override
	public Mixture findLastMixture() {
		return (Mixture) this.getSession().createQuery("select m from Mixture as m where m.id = (select max(a.id) from Mixture a)").uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mixture> findByRequestCode(String code) {
		return this.getSession().createQuery("select distinct m from Mixture m join fetch m.requests as r where r.code = :code").setString("code", code).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mixture> findByRequestCode(String code, int start, int length, String sortBy, Boolean desc) {
		String sortDirection = "asc";

		if (desc)
			sortDirection = "desc";

		Query q = this.getSession().createQuery("select distinct m from Mixture m join fetch m.requests as r where r.code = :code order by m." + sortBy + " " + sortDirection)
				.setString("code", code);
		q.setFirstResult(start);
		q.setMaxResults(length);

		return q.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mixture> searchByProperties(String sampleCode, String description, String origin, String requestCode, String sampleType, String storagePlace) {
		Query q = this.getSession().createQuery(
				"select distinct m from Mixture m left join fetch m.requests as r where r.code like :requestCode and m.sampleType.name like :sampleType "
						+ "and m.code like :sampleCode "
						+ "and m.description like :description and m.origin like :origin and (m.storagePlace like :storagePlace or m.storagePlace is null) ");

		q.setString("requestCode", requestCode + "%");
		q.setString("sampleType", sampleType + "%");
		q.setString("sampleCode", sampleCode + "%");
		q.setString("description", description + "%");
		q.setString("origin", origin + "%");
		q.setString("storagePlace", storagePlace + "%");

		return q.list();
	}

}
